/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.nucarf;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.dongjiang.tax.system.utils.HttpUtil;
import org.jeecg.modules.third.nucarf.constant.NucarEtcConstant;
import org.jeecg.modules.third.nucarf.dto.NucarEtcRequestDTO;
import org.jeecg.modules.third.nucarf.dto.NucarEtcResponderDTO;
import org.jeecg.modules.wlhy.hynucaretcinvoice.entity.HyNucaretcInvoice;
import org.jeecg.modules.wlhy.hynucaretcinvoice.service.IHyNucaretcInvoiceService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 万金油外调车ETC开票
 * @author duanlikao
 * @created 2021/4/23
 */
@Slf4j
@Service
public class NucarfEtcService {

    @Value(value="${etcwd.baseUrl}")
    private String baseUrl ;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IHyShippingNoteService shippingNoteService;

    @Autowired
    private IHyNucaretcInvoiceService hyNucaretcInvoiceService;


    private static final Logger LOGGER = LoggerFactory.getLogger(NucarfEtcService.class);

    public static void main(String[] args) {

//        System.out.println(
//                DateUtils.dateTimeToStringT(new Date())
//        );


        boolean a =  new NucarfEtcService().test();
//        NucarEtcResponderDTO a =  new NucarfEtcService().findInvoiceByNum("YD2021042100027");
        System.out.println(a);
    }

    public  boolean  test() {

        HyShippingNote hyShippingNote =  new HyShippingNote();
        hyShippingNote.setShippingNoteNumber("YD2021042100027");

        hyShippingNote.setCostPayTotal( new BigDecimal("13446.43"));

        hyShippingNote.setSendAddress("山西省吕梁市中阳县");
        hyShippingNote.setReceiveAddress("辽宁省锦州市义县九道岭镇四方台村 ");
        HyVehicle hyVehicle = new HyVehicle();

        hyVehicle.setVehicleNumber("辽PC7279");
        hyVehicle.setVehiclePlateColorCode("2");

        NucarEtcRequestDTO nucarEtcRequestDTO = new NucarEtcRequestDTO ();
        nucarEtcRequestDTO.setWaybillNum(hyShippingNote.getShippingNoteNumber());
        nucarEtcRequestDTO.setPlateNum(hyVehicle.getVehicleNumber());
        nucarEtcRequestDTO.setPlateColor("2".equals(hyVehicle.getVehiclePlateColorCode()) ? 1 : 0);
        nucarEtcRequestDTO.setSourceAddr(hyShippingNote.getSendAddress());
        nucarEtcRequestDTO.setDestAddr(hyShippingNote.getReceiveAddress());
        nucarEtcRequestDTO.setStartTime("2021-04-21T18:18:46" );
        nucarEtcRequestDTO.setEndTime( "2021-04-22T16:15:16");
        BigDecimal num = new BigDecimal("100");
        Long fee = hyShippingNote.getCostPayTotal().multiply(num).setScale( 0, BigDecimal.ROUND_DOWN ).longValue();
        nucarEtcRequestDTO.setFee( fee);
        String resultStart  = new  NucarfEtcService().waybillStart( nucarEtcRequestDTO );
        Boolean resultEnd = false;
        if(resultEnd){
            NucarEtcRequestDTO endNucarEtcRequestDTO = new NucarEtcRequestDTO ();
            endNucarEtcRequestDTO.setWaybillNum(hyShippingNote.getShippingNoteNumber());
            endNucarEtcRequestDTO.setRealDestAddr(hyShippingNote.getReceiveAddress());
            endNucarEtcRequestDTO.setEndTime( "2021-04-22T16:15:16");
//            String  resultEnd  = new  NucarfEtcService().waybillEnd( endNucarEtcRequestDTO );
        }
//        if( resultStart && resultEnd){
//            return true;
//        }
        return false;
    }
    /**
     * 获取系统Token
     * @return
     */
    private String getToken(){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getEtcwdIzUse()){
            throw new JeecgBootException("万金油外调车ETC服务暂未开启,请联系管理。");
        }

        Object tokenObject  =
                redisUtil.hasKey(NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY) ?
                redisUtil.get(NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY) : null;
        if (tokenObject != null ) {
            return tokenObject.toString();
        }
        try {
            String url = baseUrl+ NucarEtcConstant.ETC_API_PATH_GETTOKEN;
            Map <String, String> map = new HashMap <>();
            map.put("corpId",systemConfig.getEtcwdCorpId());
            map.put("appId",systemConfig.getEtcwdAppId() );
            map.put("secret",systemConfig.getEtcwdSecret());
            // map.put("refreshToken","");
            String jsonString = JSONObject.toJSONString(map);

            log.info("获取token请求参数 -> {} {}", url, jsonString);
            String res = HttpUtil.doNewPost(url, jsonString);
            log.info("获取token请求回执 <- {} {}", res);

            if(StringUtils.isNotEmpty(res)){
                JSONObject result = JSONObject.parseObject(res);
                String code = result.getString("code") ;
                if( "0".equals(code)){
                    JSONObject resultDataObject = result.getJSONObject("data");
                    if(resultDataObject == null){
                        return null;
                    }
                    String token =  resultDataObject.getString("accessToken");
                    if(StringUtils.isNotEmpty(token)){
                        int expires = NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY_EXPIRE;
                        Integer  expiresIn = resultDataObject.getInteger("expiresIn");
                        if(expiresIn != null && expiresIn > 0){
                            expires = expiresIn;
                        }
                        redisUtil.set(NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY, token , expires);
                        return token;
                    }
                }else{
                    String message = result.getString("message") ;
                    throw new JeecgBootException(message);
                }
            }
        } catch (Exception e) {
            LOGGER.info("NucarfEtcService getTaxToken Exception | {}" ,e.getMessage());
        }
        return null;
    }

    /**
     *     1蓝 2 黄
     *     蓝色	0
     *     黄色	1
     * 运单开始接口。
     * @param nucarEtcRequestDTO
     * @return
     */
    public String waybillStart(NucarEtcRequestDTO nucarEtcRequestDTO ){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getEtcwdIzUse()){
            throw new JeecgBootException("万金油外调车ETC服务暂未开启,请联系管理。");
        }
        String  token = getToken();
        if(StringUtils.isEmpty(token)){
            throw new JeecgBootException("万金油外调车ETC服务获取Token失败,请联系管理。");
        }
        try {
            String url = baseUrl+ NucarEtcConstant.ETC_API_PATH_WAYBILLSTART+NucarEtcConstant.ETC_API_PATH_SUPPLEMENT+token;
            String jsonString = JSONObject.toJSONString(nucarEtcRequestDTO);
//            LOGGER.info("NucarfEtcService waybillStart url | {}" ,url);
//            LOGGER.info("NucarfEtcService waybillStart request | {}" ,jsonString);

            log.info("万金油外调车Start请求参数-> {} {}", url, nucarEtcRequestDTO.getWaybillNum());
            String res = HttpUtil.doNewPost(url, jsonString);
            log.info("万金油外调车Start请求回执<- {} {}", res);
//            LOGGER.info("NucarfEtcService waybillStart result | {}" ,res);
            if(StringUtils.isNotEmpty(res)){
                JSONObject result = JSONObject.parseObject(res);
                Integer code = result.getInteger("code") ;
                if(code==403){
                    redisUtil.del(NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY);
                }
                return res;
            }
        } catch (Exception e) {
            LOGGER.info("NucarfEtcService waybillStart Exception | {}" ,e.getMessage());
        }
        return StringUtils.EMPTY;
    }

    /**
     * 运单结束信息更新接口。
     * @param nucarEtcRequestDTO
     * @return
     */
    public String waybillEnd(NucarEtcRequestDTO nucarEtcRequestDTO ){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getEtcwdIzUse()){
            throw new JeecgBootException("万金油外调车ETC服务暂未开启,请联系管理。");
        }
        String  token = getToken();
        if(StringUtils.isEmpty(token)){
            throw new JeecgBootException("万金油外调车ETC服务获取Token失败,请联系管理。");
        }
        try {

            String url = baseUrl+ NucarEtcConstant.ETC_API_PATH_WAYBILLEND+NucarEtcConstant.ETC_API_PATH_SUPPLEMENT+token;
            String jsonString = JSONObject.toJSONString(nucarEtcRequestDTO);
//            LOGGER.info("NucarfEtcService waybillEnd url | {}" ,url);
//            LOGGER.info("NucarfEtcService waybillEnd request | {}" ,jsonString);
            log.info("万金油外调车End请求参数-> {} {}", url, nucarEtcRequestDTO.getWaybillNum());
            String res = HttpUtil.doNewPost(url, jsonString);
            log.info("万金油外调车End请求回执<- {} {}", res);
//            LOGGER.info("NucarfEtcService waybillEnd result | {}" ,res);
            if(StringUtils.isNotEmpty(res)){
                JSONObject result = JSONObject.parseObject(res);
                Integer code = result.getInteger("code") ;
                if(code==403){
                    redisUtil.del(NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY);
                }
                return res;
            }
        } catch (Exception e) {
            LOGGER.info("NucarfEtcService waybillEnd Exception | {}" ,e.getMessage());
        }
        return StringUtils.EMPTY;
    }

    /**
     * 查询运单发票数据
     * @param waybillNum
     * @return
     */
    public NucarEtcResponderDTO findInvoiceByNum(String waybillNum ){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getEtcwdIzUse()){
            throw new JeecgBootException("万金油外调车ETC服务暂未开启,请联系管理。");
        }
        String  token = getToken();
        if(StringUtils.isEmpty(token)){
            throw new JeecgBootException("万金油外调车ETC服务获取Token失败,请联系管理。");
        }
        try {

            String url = baseUrl+ NucarEtcConstant.ETC_API_PATH_FINDINVOICEBYNUM+NucarEtcConstant.ETC_API_PATH_SUPPLEMENT+token;
            Map <String, String> map = new HashMap <>();
            map.put("waybillNum",waybillNum);
            String jsonString = JSONObject.toJSONString(map);

            log.info("万金油外调车查询发票请求参数-> {} {}", url, jsonString);
            String res = HttpUtil.doNewPost(url, jsonString);
            log.info("万金油外调车查询发票请求回执<- {}", res);
//            String res =  "{\"code\":0,\"msg\":\"OK\",\"data\":{\"plateNum\":\"京A88888\",\"vehicleType\":1,\"waybillNum\":\"202981011111111\",\"waybillStatus\":3,\"waybillStartTime\":\"2020-07-23T06:47:23\",\"waybillEndTime\":\"2020-07-23T06:47:23\",\"result\":[{\"invoiceNum\":\"2020111111\",\"invoiceCode\":\"13111111\",\"invoiceMakeTime\":\"2020-07-23T06:47:23\",\"enStation\":\"上海XX收费站\",\"exStation\":\"北京XX收费站\",\"enDate\":\"2020-07-23\",\"exDate\":\"2020-07-23\",\"exTime\":\"2020-07-23T06:47:23\",\"fee\":10000,\"totalTaxAmount\":200,\"plateNum\":\"京 A88888\",\"vehicleType\":0,\"buyerName\":null,\"buyerTaxpayerCode\":null,\"sellerName\":\"济南市XXXX有限公司\",\"sellerTaxpayerCode\":\"91430111111111\",\"waybillNum\":\"YD2021032900005\",\"waybillStartTime\":\"2020-07-23T06:47:23\",\"waybillEndTime\":\"2020-07-23T06:47:23\",\"totalAmount\":10200,\"taxRate\":0.03,\"invoiceType\":\"可抵扣发票\",\"invoiceUrl\":null,\"invoiceHtmlUrl\":null},{\"invoiceNum\":\"2020222222\",\"invoiceCode\":\"13222222\",\"invoiceMakeTime\":\"2020-07-23T06:47:23\",\"enStation\":\"上海XX收费站\",\"exStation\":\"北京XX收费站\",\"enDate\":\"2020-07-23\",\"exDate\":\"2020-07-23\",\"exTime\":\"2020-07-23T06:47:23\",\"fee\":10000,\"totalTaxAmount\":200,\"plateNum\":\"京 A88888\",\"vehicleType\":0,\"buyerName\":null,\"buyerTaxpayerCode\":null,\"sellerName\":\"济南市XXXX有限公司\",\"sellerTaxpayerCode\":\"91430111111111\",\"waybillNum\":\"YD2021032900005\",\"waybillStartTime\":\"2020-07-23T06:47:23\",\"waybillEndTime\":\"2020-07-23T06:47:23\",\"totalAmount\":10200,\"taxRate\":0.03,\"invoiceType\":\"可抵扣发票\",\"invoiceUrl\":null,\"invoiceHtmlUrl\":null}]}}";
//            LOGGER.info("NucarfEtcService findInvoiceByNum result | {}" ,res);
            if(StringUtils.isNotEmpty(res)){
                JSONObject result = JSONObject.parseObject(res);
                Integer code = result.getInteger("code") ;
                if(code==403){
                    redisUtil.del(NucarEtcConstant.ETC_API_NUCAR_TOKEN_KEY);
                }
                if( code == 0) {
                    JSONObject data = result.getJSONObject("data");
                    if(data!=null){
                        return data.toJavaObject(NucarEtcResponderDTO.class);
                    }
                }
            }
            return null;
        } catch (Exception e) {
            LOGGER.info("NucarfEtcService findInvoiceByNum Exception | {}" ,e.getMessage());
        }
        return null;
    }


    @Transactional
    public void saveEtcInvoice(List<HyNucaretcInvoice> result, HyShippingNote hyShippingNote) {
        hyNucaretcInvoiceService.saveBatch(result);
        hyShippingNote.setWaybillStatus("3");
        shippingNoteService.updateById(hyShippingNote);
    }
}
